<?php

namespace app\seller\controller;

use app\common\controller\Seller;
use think\Db;
use think\Exception;

/**
 * 订单表
 *
 * @icon fa fa-circle-o
 */
class Order extends Seller
{
	
	protected $searchFields = true;
	/**
	 * Order模型对象
	 */
	protected $model = null;
	protected $relationSearch = true;
	
	public function _initialize()
	{
		parent::_initialize();
		$this->model = new \app\common\model\Order();
		
		$config = [
			"orderStatusList" => $this->model->getOrderStatusList(),
			"shippingStatusList" => $this->model->getShippingStatusList(),
			"payStatusList" => $this->model->getPayStatusList(),
			"orderPromTypeList" => $this->model->getOrderPromTypeList(),
			"isDistributList" => $this->model->getIsDistributList(),
			"deletedList" => $this->model->getDeletedList(),
			'payTypeList' => \app\common\model\Payment::$_pay_type,
		];
		
		$this->assignconfig($config);
		$this->assign($config);
	}
	
	/**
	 * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
	 * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
	 * 需要将application/admin/library/traits/Seller.php中对应的方法复制到当前控制器,然后进行修改
	 */
	
	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax()) {
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('pkey_name')) {
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			$total = $this->model
				->with('user,business')
				->where($where)
				->where(['fs_order.business_id' => $this->auth->id])
				->order($sort, $order)
				->count();
			
			$list = $this->model
				->with('user,business')
				->where($where)
				->where(['fs_order.business_id' => $this->auth->id])
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
			
			$list = collection($list)->toArray();
			$result = array("total" => $total, "rows" => $list);
			
			return json($result);
		}
		$countList = $this->model->countList(['merid' => $this->auth->merid, 'business_id' => $this->auth->id]);
		
		return $this->view->fetch('index', [
			'countList' => $countList,
		]);
	}
	
	
	/**
	 * 编辑
	 */
	public function edit($ids = null)
	{
		$row = $this->model->alias('o')
			->join('user u', 'o.user_id = u.id', 'left')
			->join('business b', 'o.business_id = b.id', 'left')
			->join('order_address a', 'o.id = a.order_id', 'left')
			->join('shipping s', 'o.shipping_id = s.id', 'left')
			->join('area p', 'a.province_id = p.id', 'left')
			->join('area c', 'a.city_id = c.id', 'left')
			->join('area ar', 'a.area_id = ar.id', 'left')
			->where(['o.id' => $ids, 'o.business_id' => $this->auth->id])
			->field('o.*, u.username, a.recipients, a.mobile, a.address, p.areaname as pname, c.areaname as cname, ar.areaname as aname, a.province_id, a.city_id, a.area_id, b.name as bname, s.name as shipping_name')
			->find();
//			->toArray();
		
		$goods = Db::name('orderGoods')
			->where(['order_id' => $ids])
			->select();
		
		$provinces = Db::name('area')->where(['parentid' => 0])->field('id,areaname')->select();
		$citys = Db::name('area')->where(['parentid' => $row['province_id']])->field('id,areaname')->select();
		$areas = Db::name('area')->where(['parentid' => $row['city_id']])->field('id,areaname')->select();
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
			if (!in_array($row[$this->dataLimitField], $adminIds)) {
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			$address = $this->request->post("address/a");
			if ($params) {
				Db::startTrans();
				try {
					//是否采用模型验证
					if ($this->modelValidate) {
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
						$row->validate($validate);
					}
					
					if($address){
						$addRes = Db::name('orderAddress')->where(['order_id' => $ids])->update($address);
						if($addRes === false){
							$this->error('更改出错地址出错');
						}
					}
					
					$model = new \app\common\model\Order();
					if($row['order_status'] == $model::STATUS_WAIT_DELIVERY && $params['shipping_id']){
						if(!$params['shipping_code']){
							throw new Exception('请填写物流单号');
						}
						
						//更改订单状态为卖家已发货
						$params['order_status'] = $model::STATUS_WAIT_SIGN;
						$params['shipping_status'] = $model::SHIPPING_STATUS_W;
						$params['shipping_time'] = time();
					}
					
					$result = $row->allowField(true)->save($params);
					if ($result === false) {
						throw new Exception($row->getErrot());
					}
					Db::commit();
					$this->success();
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		
		$shippings = Db::name('shipping')->field('id,name')->order(['name' => 'asc'])->select();
		return $this->view->fetch('edit', [
			'row' => $row,
			'goods' => $goods,
			'provinces' => $provinces,
			'citys' => $citys,
			'areas' => $areas,
			'shippings' => $shippings,
		]);
	}
	
	
	/**
	 * 发货
	 */
	public function ship($ids = null)
	{
		$row = $this->model->alias('o')
			->join('user u', 'o.user_id = u.id', 'left')
			->join('business b', 'o.business_id = b.id', 'left')
			->join('order_address a', 'o.id = a.order_id', 'left')
			->join('shipping s', 'o.shipping_id = s.id', 'left')
			->join('area p', 'a.province_id = p.id', 'left')
			->join('area c', 'a.city_id = c.id', 'left')
			->join('area ar', 'a.area_id = ar.id', 'left')
			->where(['o.id' => $ids, 'o.business_id' => $this->auth->id])
			->field('o.*, u.username, a.recipients, a.mobile, a.address, p.areaname as pname, c.areaname as cname, ar.areaname as aname, a.province_id, a.city_id, a.area_id, b.name as bname, s.name as shipping_name, o.order_prom_type')
			->find();
		
		$goods = Db::name('orderGoods')
			->where(['order_id' => $ids])
			->select();
		
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		
		if($row['order_status'] != \app\common\model\Order::STATUS_WAIT_DELIVERY) {
			$this->error('非待发货订单');
		}
		
		
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
			if (!in_array($row[$this->dataLimitField], $adminIds)) {
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			if ($params) {
				Db::startTrans();
				try {
					
					$model = new \app\common\model\Order();
					if(!$params['shipping_code']){
						throw new Exception('请填写物流单号');
					}
					
					//更改订单状态为卖家已发货
					$params['order_status'] = $model::STATUS_WAIT_SIGN;
					$params['shipping_status'] = $model::SHIPPING_STATUS_W;
					$params['shipping_time'] = time();
					
					$result = $row->allowField(true)->save($params);
					if ($result === false) {
						throw new Exception($row->getErrot());
					}
					
					$shipping = Db::name('shipping')->find($params['shipping_id']);
					$shipRes = Db::name('orderShipping')
						->insert([
							'order_id' => $ids,
							'shipping_id' => $params['shipping_id'],
							'shipping_code' => $shipping['code'],
							'shipping_no' => $params['shipping_code'],
							'create_time' => time(),
							'update_time' => time()
						]);
					
					//如果为分期商品，更改分期商品发货任务
					if($row['order_prom_type'] == \app\common\model\Order::ORDER_TYPE_STAGING) {
						$taskModel = new \app\common\model\DeliveryTask();
						$where['order_id'] = $row['id'];
						$task = $taskModel->where($where)->find();
						
						$taskRes = $taskModel->save([
							'delivery_number' => 1,
							'next_time' => strtotime('+'.$task['days'].' days')
						],$where);
						
						if(!$taskRes) {
							throw new Exception('更改分期发货任务出错');
						}
					}
					
					//添加通知
					\app\common\model\WebMail::addMail($row['merid'], $row['user_id'], '快递：亲，您所购买的宝贝已经发出，快递单号为'.$shipping['name'].$params['shipping_code'].'，请注意查收！欢迎下次光临');
					Db::commit();
					$this->success();
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		
		$shippings = Db::name('shipping')->field('id,name')->order(['name' => 'asc'])->select();
		return $this->view->fetch('ship', [
			'row' => $row,
			'goods' => $goods,
			'shippings' => $shippings,
		]);
	}
	
	
}
